package com.ruoyi.sevenInterfaces.service.impl;

import com.ruoyi.common.config.DbInterfaceConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sevenInterfaces.domain.*;
import com.ruoyi.sevenInterfaces.domain.dto.EventTargetDto;
import com.ruoyi.sevenInterfaces.domain.vo.EventTargetVO;
import com.ruoyi.sevenInterfaces.domain.vo.ReqVo;
import com.ruoyi.sevenInterfaces.domain.vo.WebDateVo;
import com.ruoyi.sevenInterfaces.service.SevenInterfacesService;
import com.ruoyi.sevenInterfaces.utils.HttpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author wsl
 * @Date 2025-02-25 10:00
 * @Version 1.0
 */
@Service
public class SevenInterfacesServiceImpl implements SevenInterfacesService {

    @Autowired
    private DbInterfaceConfig dbInterfaceConfig;
    @Override
    public List<String> getEventName(Integer type) {

        //暂定只提供事件名称，type== 7
        switch (type) {
            case 7:
                StringBuilder sb = new StringBuilder("select SJMC as name from J_KY_S_SJB");
                List<Map<String, String>> targetNameList = (List<Map<String, String>>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), Map.class);
                List<String> targetNames = targetNameList.stream().map(map -> map.get("name")).collect(Collectors.toList());
                return targetNames;
            default :
                    return new ArrayList<>();
        }

    }

    @Override
    public List<EventTargetVO> getMbAndDate(String name) {

        StringBuilder sb = new StringBuilder("select id eventId, SJMC eventName , SJKSSJ startTime, SJJSSJ endTime   from J_KY_S_SJB where SJMC = '").append(name).append("'");
        List<EventTargetVO> eventTargetVOList = (List<EventTargetVO>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), EventTargetVO.class);
        eventTargetVOList.forEach(eventTargetVO -> {
            //todo  条件 是否合理
            StringBuilder sb1 = new StringBuilder("select id, MBLX targetType, MBNR targetContent from J_KY_S_SJMBXX where id = ").append(eventTargetVO.getEventId()).append(" and (MBLX = '舰船' or MBLX = '飞机')");
            List<EventTargetVO.EventTargetInfo> eventTargetInfos = (List<EventTargetVO.EventTargetInfo>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb1.toString()), EventTargetVO.EventTargetInfo.class);
            eventTargetVO.setEventTargetInfo(eventTargetInfos);
        });
        return eventTargetVOList;

    }

    @Override
    public List<String> getTargetName() {

        String sql = "select MBMC as targetName from J_KY_S_MBJBXXB where MBFL in (2, 3)";
        List<Map<String, String>> targetNameMapList = (List<Map<String, String>>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sql), Map.class);
        List<String> targetName = targetNameMapList.stream().map(map -> map.get("targetName")).collect(Collectors.toList());
        return targetName;
    }

    @Override
    public TableDataInfo getTargetDynamicsInfoHistoryByShip(EventTargetDto eventTargetDto) {

        Integer pageNum = eventTargetDto.getPageNum();
        Integer pageSize = eventTargetDto.getPageSize();

        String[] targetNameArray = eventTargetDto.getTargetName() != null ? eventTargetDto.getTargetName().split(",") : new String[0];


        StringBuilder sb = new StringBuilder("select    ais.mmsi as mmsi_icao, ais.status, ais.base_time as base_time, ais.lon, ais.lat, ais.speed, ais.way, null as geo_height, tbi.target_name as target_name, tbi.target_class as type " +
                "from ais_dynamics_info ais " +
                "left join equip_ship es " +
                "on es.mmsi = ais.mmsi " +
                "left join target_base_info tbi on es.id = tbi.target_id and tbi.target_class = '3'  " +
                "WHERE 1 = 1 ");
                if(targetNameArray.length > 0){
                    sb.append("and tbi.target_name IN (");
                    for (String targetName : targetNameArray) {
                        sb.append("'").append(targetName).append("',");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(")");
                }
                if(eventTargetDto.getStartTime() != null && eventTargetDto.getEndTime() != null) {
                    sb.append(" and (ais.base_time > '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getStartTime())).append("'  and ais.base_time < '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getEndTime())).append("')");
                }
//                sb.append("UNION " +
//                        "select ads.icao as mmsi_icao, ads.status, ads.base_time as base_time, ads.lon, ads.lat, ads.speed, ads.way, ads.geo_height as geo_height, tbi.target_name as target_name, tbi.target_class as type " +
//                        "from ads_dynamics_info ads " +
//                        "left join equip_aircraft ea " +
//                        "on ads.icao = ea.mmsi " +
//                        "left join target_base_info tbi " +
//                        "on ea.id = tbi.target_id and tbi.target_class = '2'  " +
//                        "WHERE 1 = 1 ");
//                if(targetNameArray.length > 0){
//                    sb.append("and tbi.target_name IN (");
//                    for (String targetName : targetNameArray) {
//                        sb.append("'").append(targetName).append("',");
//                    }
//                    sb.deleteCharAt(sb.length() - 1);
//                    sb.append(")");
//                }
//                if(eventTargetDto.getStartTime() != null && eventTargetDto.getEndTime() != null) {
//                    sb.append(" and (ads.base_time > '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getStartTime())).append("'  and ads.base_time < '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getEndTime())).append("')");
//                }
                sb.append(" ORDER BY base_time desc  ");
                if(pageNum != null && pageSize != null){
                    sb.append(" limit ").append(pageSize).append(" offset ").append((pageNum - 1) * pageSize);
                }
        List<EventTarget> eventTargets = (List<EventTarget>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), EventTarget.class);

        StringBuilder countSql = new StringBuilder("");
        if(pageNum != null && pageSize != null){
            countSql.append("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        } else {
            countSql.append("select count(*) as count from (").append(sb.toString()).append(") cursor");
        }
//        StringBuffer countSql = new StringBuffer("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        Map<String, Integer> countMap = (Map<String, Integer>) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(countSql.toString()), Map.class);
        for (EventTarget eventTarget : eventTargets) {
            eventTarget.setEventName(eventTargetDto.getEventName());
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(eventTargets);
        rspData.setTotal(countMap.get("count"));
        return rspData;
    }

    public TableDataInfo getTargetDynamicsInfoHistoryByPlan(EventTargetDto eventTargetDto) {

        Integer pageNum = eventTargetDto.getPageNum();
        Integer pageSize = eventTargetDto.getPageSize();

        String[] targetNameArray = eventTargetDto.getTargetName() != null ? eventTargetDto.getTargetName().split(",") : new String[0];


        StringBuffer sb = new StringBuffer("");
//        sb.append("select    ais.mmsi as mmsi_icao, ais.status, ais.base_time as base_time, ais.lon, ais.lat, ais.speed, ais.way, null as geo_height, tbi.target_name as target_name, tbi.target_class as type " +
//                "from ais_dynamics_info ais " +
//                "left join equip_ship es " +
//                "on es.mmsi = ais.mmsi " +
//                "left join target_base_info tbi on es.id = tbi.target_id and tbi.target_class = '3'  " +
//                "WHERE 1 = 1 ");
//        if(targetNameArray.length > 0){
//            sb.append("and tbi.target_name IN (");
//            for (String targetName : targetNameArray) {
//                sb.append("'").append(targetName).append("',");
//            }
//            sb.deleteCharAt(sb.length() - 1);
//            sb.append(")");
//        }
//        if(eventTargetDto.getStartTime() != null && eventTargetDto.getEndTime() != null) {
//            sb.append(" and (ais.base_time > '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getStartTime())).append("'  and ais.base_time < '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getEndTime())).append("')");
//        }
                sb.append(" " +
                        "select ads.icao as mmsi_icao, ads.status, ads.base_time as base_time, ads.lon, ads.lat, " +
                        "ads.speed, ads.way, ads.geo_height as geo_height, tbi.target_name as target_name, tbi.target_class as type " +
                        "from ads_dynamics_info ads " +
                        "left join equip_aircraft ea " +
                        "on ads.icao = ea.mmsi " +
                        "left join target_base_info tbi " +
                        "on ea.id = tbi.target_id and tbi.target_class = '2'  " +
                        "WHERE 1 = 1 ");
                if(targetNameArray.length > 0){
                    sb.append("and tbi.target_name IN (");
                    for (String targetName : targetNameArray) {
                        sb.append("'").append(targetName).append("',");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(")");
                }
                if(eventTargetDto.getStartTime() != null && eventTargetDto.getEndTime() != null) {
                    sb.append(" and (ads.base_time > '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getStartTime())).append("'  and ads.base_time < '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getEndTime())).append("')");
                }
        sb.append(" ORDER BY base_time desc  ");
        if(pageNum != null && pageSize != null){
            sb.append(" limit ").append(pageSize).append(" offset ").append((pageNum - 1) * pageSize);
        }
        List<EventTarget> eventTargets = (List<EventTarget>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), EventTarget.class);

        StringBuilder countSql = new StringBuilder("");
        if(pageNum != null && pageSize != null){
            countSql.append("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        } else {
            countSql.append("select count(*) as count from (").append(sb.toString()).append(") cursor");
        }
//        StringBuffer countSql = new StringBuffer("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        Map<String, Integer> countMap = (Map<String, Integer>) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(countSql.toString()), Map.class);
        for (EventTarget eventTarget : eventTargets) {
            eventTarget.setEventName(eventTargetDto.getEventName());
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(eventTargets);
        rspData.setTotal(countMap.get("count"));
        return rspData;
    }

    @Override
    public TableDataInfo getTargetInfo(EventTargetDto eventTargetDto) {
        Integer pageNum = eventTargetDto.getPageNum();
        Integer pageSize = eventTargetDto.getPageSize();

        String[] targetNames = eventTargetDto.getTargetName() != null ? eventTargetDto.getTargetName().split(",") : new String[0];

        StringBuilder sb = new StringBuilder("SELECT id,area,altitude,target_name,geodetic_height,target_id,latitude,belonging_region,target_type,target_nickname,target_class,country_affiliation,other_param,longitude " +
                "FROM target_base_info ");
        if(targetNames.length > 0){
            sb.append("where target_name in (");
            for (String targetName : targetNames) {
                sb.append("'").append(targetName).append("',");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append(")");
        }
        if(pageNum != null && pageSize != null){
            sb.append(" limit ").append(pageSize).append(" offset ").append((pageNum - 1) * pageSize);
        }
        List<TargetBaseInfo> targetBaseInfos = (List<TargetBaseInfo>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), TargetBaseInfo.class);
        List<EquipAllInfoDto> euqEquipAllInfoDtos = new ArrayList<>();
        for (TargetBaseInfo targetBaseInfo : targetBaseInfos) {

            EquipAllInfoDto allInfoDto = new EquipAllInfoDto();
            BeanUtils.copyProperties(targetBaseInfo, allInfoDto);
            StringBuilder equipSql = new StringBuilder("SELECT id AS equipBaseInfoId,preview,remark,update_time,create_by,update_by,create_time,target_position,other_param FROM equip_base_info WHERE id=").append(targetBaseInfo.getTargetId());
            EquipBaseInfo equipBaseInfo = (EquipBaseInfo) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(equipSql.toString()), EquipBaseInfo.class);
            if(equipBaseInfo == null){
                continue;
            }
            if(targetBaseInfo.getTargetClass() == 2){
                StringBuilder planSql = new StringBuilder("SELECT id AS equipBaseInfoId,plane_length,mmsi,remark,update_time,people_num,plane_radius,plane_height,create_by,plane_speed,update_by,create_time,plane_width FROM equip_aircraft WHERE id=").append(targetBaseInfo.getTargetId());
                EquipAircraft equipAircraft = (EquipAircraft) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(planSql.toString()), EquipAircraft.class);
                equipBaseInfo.setTAti(equipAircraft);
            }
            if(targetBaseInfo.getTargetClass() == 3){
                StringBuilder shipSql = new StringBuilder("SELECT id AS equipBaseInfoId,mmsi,ship_width,remark,update_time,max_speed,water_quantity,people_num,ship_code,ship_length,create_by,water_par,update_by,create_time FROM equip_ship WHERE id=").append(targetBaseInfo.getTargetId());
                EquipShip equipShip = (EquipShip) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(shipSql.toString()), EquipShip.class);
                equipBaseInfo.setTAti(equipShip);
            }
            BeanUtils.copyProperties(equipBaseInfo, allInfoDto);
            allInfoDto.setEventName(eventTargetDto.getEventName());
            euqEquipAllInfoDtos.add(allInfoDto);
        }

        StringBuilder countSql = new StringBuilder("");
        if(pageNum != null && pageSize != null){
            countSql.append("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        } else {
            countSql.append("select count(*) as count from (").append(sb.toString()).append(") cursor");
        }
//        StringBuffer countSql = new StringBuffer("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        Map<String, Integer> countMap = (Map<String, Integer>) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(countSql.toString()), Map.class);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(euqEquipAllInfoDtos);
        rspData.setTotal(countMap.get("count"));
        return rspData;
    }

    @Override
    public TableDataInfo getWebData(EventTargetDto eventTargetDto) {

        Integer pageNum = eventTargetDto.getPageNum();
        Integer pageSize = eventTargetDto.getPageSize();

        String[] targetNames = eventTargetDto.getTargetName() != null ? eventTargetDto.getTargetName().split(",") : new String[0];

        StringBuilder sb = new StringBuilder("SELECT " +
                "DISTINCT ( nt.network_id ) AS networdid " +
                "FROM network_target nt " +
                "LEFT JOIN target_base_info bti " +
                "ON nt.target_id = bti.ID " +
                "AND nt.relation_type = 4 " +
                "LEFT JOIN target_event te " +
                "ON nt.target_id = te.event_id  " +
                "AND nt.relation_type = 2  " +
                "left join network_data nd " +
                "on nt.network_id = nd.network_id " +
                "WHERE 1 = 1  ");
        if(targetNames.length > 0){
            sb.append(" and target_name in (");
            for (String targetName : targetNames) {
                sb.append("'").append(targetName).append("',");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append(")");
        }
        if(StringUtils.isNotBlank(eventTargetDto.getEventName())){
            if(targetNames.length > 0){
                sb.append(" or ");
            }
            sb.append(" te.event_name LIKE '%").append(eventTargetDto.getEventName()).append("%' ");
        }
        if(eventTargetDto.getStartTime() != null && eventTargetDto.getEndTime() != null){
            if(!(targetNames.length > 0) && StringUtils.isBlank(eventTargetDto.getEventName())){
                sb.append(" and ");
            } else {
                sb.append(" or ");
            }
            sb.append("  (nd.release_time > '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getStartTime())).append("'  and nd.release_time < '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, eventTargetDto.getEndTime())).append("')");
        }
        if(pageNum != null && pageSize != null){
            sb.append(" limit ").append(pageSize).append(" offset ").append((pageNum - 1) * pageSize);
        }
        List<Map<String, Integer>> networdIds = (List<Map<String, Integer>>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), Map.class);
        List<Integer> networdids = networdIds.stream().map(map -> map.get("networdid")).collect(Collectors.toList());

        List<WebDateVo> webDateVos = new ArrayList<>();
        for (Integer networdid : networdids) {
            WebDateVo webDateVo = new WebDateVo();
            webDateVo.setNetWordId(networdid);

            StringBuilder eventNameSql = new StringBuilder("SELECT te.event_name AS eventname  FROM network_target nt INNER JOIN target_event te ON nt.target_id = te.event_id  AND nt.relation_type = 2  WHERE nt.network_id =").append(networdid);
            List<Map<String, String>> eventNameMaps = (List<Map<String, String>>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(eventNameSql.toString()), Map.class);
            String eventname = eventNameMaps.stream().map(map -> map.get("eventname")).collect(Collectors.joining(","));
            webDateVo.setEventName(eventname);

            StringBuilder peoNameSql = new StringBuilder("SELECT tp.user_name AS username FROM network_target nt INNER JOIN target_people tp ON nt.target_id = tp.user_id AND nt.relation_type = 1 WHERE nt.network_id = ").append(networdid);
            List<Map<String, String>> peoNameMaps = (List<Map<String, String>>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(peoNameSql.toString()), Map.class);
            String peoName = peoNameMaps.stream().map(map -> map.get("username")).collect(Collectors.joining(","));
            webDateVo.setPeopleName(peoName);


            StringBuilder targetNameSql = new StringBuilder("SELECT tbi.target_name AS targetname  FROM network_target nt INNER JOIN target_base_info tbi ON nt.target_id = tbi.id  AND nt.relation_type = 4  WHERE nt.network_id = ").append(networdid);
            List<Map<String, String>> targetNameMaps = (List<Map<String, String>>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(targetNameSql.toString()), Map.class);
            String targhetNamejoin = targetNameMaps.stream().map(map -> map.get("targetname")).collect(Collectors.joining(","));
            webDateVo.setTargetName(targhetNamejoin);

            StringBuilder timeSql = new StringBuilder("select release_time as releasetime from network_data where network_id = ").append(networdid);
            Map<String, String> timeMaps = (Map<String, String>) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(timeSql.toString()), Map.class);
            webDateVo.setTargetTime(timeMaps.get("releasetime"));
            webDateVos.add(webDateVo);
        }


        StringBuilder countSql = new StringBuilder("");
        if(pageNum != null && pageSize != null){
            countSql.append("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        } else {
            countSql.append("select count(*) as count from (").append(sb.toString()).append(") cursor");
        }
//        StringBuffer countSql = new StringBuffer("select count(*) as count from (").append(sb.toString().substring(0, sb.toString().lastIndexOf("limit"))).append(") cursor");
        Map<String, Integer> countMap = (Map<String, Integer>) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(countSql.toString()), Map.class);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(webDateVos);
        rspData.setTotal(countMap.get("count"));
        return rspData;

    }
}
